package com.jinzhi.jzweb.controller.userapi;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.wxpay.service.WxPayCommonService;
import com.jinzhi.common.wxpay.utils.ConstAppId;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.domain.*;

import com.jinzhi.jzweb.domain.vo.userapi.groupActivityVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxpay.enums.OrderStatus;
import com.jinzhi.wxpay.enums.wxpay.WxNotifyType;
import com.jinzhi.wxpay.util.OrderNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author mengzhichao
 * @create 2024-05-13-9:05
 *
 *  团购活动Controller
 */
@RestController
@RequestMapping("/jzApi/ApiJazGroupProd")
public class ApiJazGroupProdController {

    @Autowired
    private JazGroupProdService jazGroupProdService; //团购活动表

    @Autowired
    private UserService userService; //用户表

    @Autowired
    private JazGroupActivityService jazGroupActivityService; //团购活动拼团表

    @Autowired
    private JazGroupActivityUserService jazGroupActivityUserService; //团购活动拼团用户表

    @Autowired
    private JazGroupOrderService jazGroupOrderService; //团购活动订单表

    @Autowired
    private JazGroupSpecsService jazGroupSpecsService; //团购活动规格表

    @Autowired
    private JazUserCommentService jazUserCommentService; //团购活动评价表

    @Autowired
    private JazShippingAddressService jazShippingAddressService; //地址表

    @Autowired
    private JazUserCommentDescriptionService JazUserCommentDescriptionService; //团购活动评价描述表

    @Autowired
    private WxPayCommonService wxPayCommonService;

    @Autowired
    private JazSysProjectService jazSysProjectService;

    @Autowired
    private JazUserOrderService jazUserOrderService;



    /**
     * 团购列表查询
     * @return
     */
    @GetMapping("/groupProdList")
    public Result<Page<JazGroupProdDO>> groupProdList(JazGroupProdDO jazGroupProdDO){
        Page<JazGroupProdDO> page = new Page<JazGroupProdDO>(jazGroupProdDO.getCurrent(),jazGroupProdDO.getSize());
        Wrapper<JazGroupProdDO> wrapper = new EntityWrapper<>();
        wrapper.eq("check_status",1); //审核通过的数据
        wrapper.eq("prod_status",1);//上架的数据
        wrapper.orderBy("sort");
        Page<JazGroupProdDO> rstPage = jazGroupProdService.selectPage(page, wrapper);
        List<JazGroupProdDO> records = rstPage.getRecords();
        for (int i =0;i<records.size();i++){
            JazGroupProdDO JazGroupProd = records.get(i);
            Date date =new Date(); //获取当前时间
            Date startTime = JazGroupProd.getStartTime(); //拼团开始时间
            Date endTime = JazGroupProd.getEndTime(); //拼团结束时间
            if (date.compareTo(startTime) > 0 && endTime.compareTo(date) > 0) {
                System.out.println("当前时间大于开始时间小于结束时间+++++++++++++++++++++++++++");
                JazGroupProd.setIsStart(0);
            }else {
                JazGroupProd.setIsStart(1);
            }
            JazGroupProd.setGroupEndTime(String.valueOf(calculateRemainingSeconds(endTime)));
            Wrapper<JazGroupSpecsDO> jazGroupSpecsDOWrapper = new EntityWrapper<>();
            jazGroupSpecsDOWrapper.eq("group_prod_id",JazGroupProd.getId());
            jazGroupSpecsDOWrapper.orderBy("group_price"); //根据拼团价格排序，最便宜的放在第一个
            List<JazGroupSpecsDO> jazGroupSpecsDOS = jazGroupSpecsService.selectList(jazGroupSpecsDOWrapper);
            if (jazGroupSpecsDOS.size()>0){
                JazGroupProd.setHomeShowMoney(jazGroupSpecsDOS.get(0).getGroupPrice());
            }
        }
        rstPage.setRecords(records);
        return Result.ok(rstPage);
    }



    /**
     * 首页团购列表查询
     * @return
     */
    @GetMapping("/groupProdListHome")
    public Result<Page<JazGroupProdDO>> groupProdListHome(JazGroupProdDO jazGroupProdDO){
        Page<JazGroupProdDO> page = new Page<JazGroupProdDO>(jazGroupProdDO.getCurrent(),jazGroupProdDO.getSize());
        Wrapper<JazGroupProdDO> wrapper = new EntityWrapper<>();
        wrapper.eq("check_status",1); //审核通过的数据
        wrapper.eq("prod_status",1);//上架的数据
        wrapper.eq("is_show",1);//首页展示的数据
        wrapper.orderBy("home_sort");
        Page<JazGroupProdDO> rstPage = jazGroupProdService.selectPage(page, wrapper);
        List<JazGroupProdDO> records = rstPage.getRecords();
        for (int i =0;i<records.size();i++){
            JazGroupProdDO JazGroupProd = records.get(i);
            Date date =new Date(); //获取当前时间
            Date startTime = JazGroupProd.getStartTime(); //拼团开始时间
            Date endTime = JazGroupProd.getEndTime(); //拼团结束时间
            if (date.compareTo(startTime) > 0 && endTime.compareTo(date) > 0) {
                System.out.println("当前时间大于开始时间小于结束时间+++++++++++++++++++++++++++");
                JazGroupProd.setIsStart(0);
            }else {
                JazGroupProd.setIsStart(1);
            }
            JazGroupProd.setGroupEndTime(String.valueOf(calculateRemainingSeconds(endTime)));
            Wrapper<JazGroupSpecsDO> jazGroupSpecsDOWrapper = new EntityWrapper<>();
            jazGroupSpecsDOWrapper.eq("group_prod_id",JazGroupProd.getId());
            jazGroupSpecsDOWrapper.orderBy("group_price"); //根据拼团价格排序，最便宜的放在第一个
            List<JazGroupSpecsDO> jazGroupSpecsDOS = jazGroupSpecsService.selectList(jazGroupSpecsDOWrapper);
            if (jazGroupSpecsDOS.size()>0){
                JazGroupProd.setHomeShowMoney(jazGroupSpecsDOS.get(0).getGroupPrice());
            }
        }
        rstPage.setRecords(records);
        return Result.ok(rstPage);
    }




    /**
     * 团购详情查询，未登录
     * @return
     */
    @GetMapping("/groupProdDetailwdl")
    public Result<JazGroupProdDO> groupProdDetailwdl(Long id){
        JazGroupProdDO jazGroupProdDO = jazGroupProdService.selectById(id); //查询团购商品详情
        Date date =new Date(); //获取当前时间
        Date startTime = jazGroupProdDO.getStartTime(); //拼团开始时间
        Date endTime = jazGroupProdDO.getEndTime(); //拼团结束时间
        if (date.compareTo(startTime) > 0 && endTime.compareTo(date) > 0) {
            System.out.println("当前时间大于开始时间小于结束时间+++++++++++++++++++++++++++");
            jazGroupProdDO.setIsStart(0);
        }else {
            jazGroupProdDO.setIsStart(1);
        }
        jazGroupProdDO.setGroupEndTime(String.valueOf(calculateRemainingSeconds(endTime)));

        Wrapper<JazGroupSpecsDO> jazGroupSpecsDOWrapper = new EntityWrapper<>();
        jazGroupSpecsDOWrapper.eq("group_prod_id",jazGroupProdDO.getId());
        jazGroupSpecsDOWrapper.orderBy("group_price"); //根据拼团价格排序，最便宜的放在第一个
        List<JazGroupSpecsDO> jazGroupSpecsDOS = jazGroupSpecsService.selectList(jazGroupSpecsDOWrapper);
        if (jazGroupSpecsDOS.size()>0){
            jazGroupProdDO.setHomeShowMoney(jazGroupSpecsDOS.get(0).getGroupPrice());
            jazGroupProdDO.setOriginalHomeShowMoney(jazGroupSpecsDOS.get(0).getOriginalPrice());
        }
        jazGroupProdDO.setIsGroup(0);
        //处理详情图
        jazGroupProdDO.setPictureList(splitStrArrayList(jazGroupProdDO.getPicture()));
        return Result.ok(jazGroupProdDO);
    }





    /**
     * 团购详情查询
     * @return
     */
    @GetMapping("/groupProdDetail")
    public Result<JazGroupProdDO> groupProdDetail(Long id){
        JazGroupProdDO jazGroupProdDO = jazGroupProdService.selectById(id); //查询团购商品详情
        Date date =new Date(); //获取当前时间
        Date startTime = jazGroupProdDO.getStartTime(); //拼团开始时间
        Date endTime = jazGroupProdDO.getEndTime(); //拼团结束时间
        if (date.compareTo(startTime) > 0 && endTime.compareTo(date) > 0) {
            System.out.println("当前时间大于开始时间小于结束时间+++++++++++++++++++++++++++");
            jazGroupProdDO.setIsStart(0);
        }else {
            jazGroupProdDO.setIsStart(1);
        }
        jazGroupProdDO.setGroupEndTime(String.valueOf(calculateRemainingSeconds(endTime)));

        Wrapper<JazGroupSpecsDO> jazGroupSpecsDOWrapper = new EntityWrapper<>();
        jazGroupSpecsDOWrapper.eq("group_prod_id",jazGroupProdDO.getId());
        jazGroupSpecsDOWrapper.orderBy("group_price"); //根据拼团价格排序，最便宜的放在第一个
        List<JazGroupSpecsDO> jazGroupSpecsDOS = jazGroupSpecsService.selectList(jazGroupSpecsDOWrapper);
        if (jazGroupSpecsDOS.size()>0){
            jazGroupProdDO.setHomeShowMoney(jazGroupSpecsDOS.get(0).getGroupPrice());
            jazGroupProdDO.setOriginalHomeShowMoney(jazGroupSpecsDOS.get(0).getOriginalPrice());
        }

        //查询该用户是否参与过拼团
                UserDO getUser = JWTUtil.getUser();
//        UserDO getUser = new UserDO();
//        getUser.setId(1685834029766819841L);
        Wrapper<JazGroupActivityDO> jazGroupActivityDOEntityWrapper = new EntityWrapper<>();
        jazGroupActivityDOEntityWrapper.eq("group_prod_id",id);
        List<JazGroupActivityDO> jazGroupActivityDOS = jazGroupActivityService.selectList(jazGroupActivityDOEntityWrapper); //查询出该商品的所有团购
        for (int i=0;i<jazGroupActivityDOS.size();i++){
            Wrapper<JazGroupActivityUserDO> jazGroupActivityUserDOEntityWrapper = new EntityWrapper<>();
            jazGroupActivityUserDOEntityWrapper.eq("group_activity_id",jazGroupActivityDOS.get(i).getId());
            jazGroupActivityUserDOEntityWrapper.eq("user_id",getUser.getId());
            JazGroupActivityUserDO jazGroupActivityUserDO = jazGroupActivityUserService.selectOne(jazGroupActivityUserDOEntityWrapper);
            if (jazGroupActivityUserDO!=null){
                jazGroupProdDO.setIsGroup(1);
            }else {
                jazGroupProdDO.setIsGroup(0);
            }
        }

        //处理详情图
        jazGroupProdDO.setPictureList(splitStrArrayList(jazGroupProdDO.getPicture()));
        return Result.ok(jazGroupProdDO);
    }




    private static String bs = ",";


    private static List<String> splitStrArrayList(String str) {
        List<String> stringList = new ArrayList<>();
        if (str != null) {
            String[] strs = str.split(bs);
            stringList.addAll(Arrays.asList(strs));
            return stringList;
        }
        return null;
    }





    /**
     * 团购商品规格查询
     * @return
     */
    @GetMapping("/sleJazGroupSpecsList")
    public Result<List<JazGroupSpecsDO>> sleJazGroupSpecsList(Long id){
        Wrapper<JazGroupSpecsDO> jazGroupSpecsDOWrapper = new EntityWrapper<>();
        jazGroupSpecsDOWrapper.eq("group_prod_id",id);
        List<JazGroupSpecsDO> jazGroupSpecsDOS = jazGroupSpecsService.selectList(jazGroupSpecsDOWrapper);
        return Result.ok(jazGroupSpecsDOS);
    }




    /**
     * 团购用户评价
     * @return
     */
    @GetMapping("/sleJazGroupUserComment")
    public Result<List<JazUserCommentDO>> sleJazGroupUserComment(Long id){
        Wrapper<JazUserCommentDO> jazUserCommentDOWrapper = new EntityWrapper<>();
        jazUserCommentDOWrapper.eq("commentd_objectid",id);
        jazUserCommentDOWrapper.eq("type",3); //团购的评论
        List<JazUserCommentDO> jazUserCommentDOS = jazUserCommentService.selectList(jazUserCommentDOWrapper);

        for (int i=0;i<jazUserCommentDOS.size();i++){
            JazUserCommentDO jazUserCommentDO = jazUserCommentDOS.get(i);

            UserDO userDO = userService.selectById(jazUserCommentDO.getCommentUserid());
            jazUserCommentDO.setUserImg(userDO.getHeadPortrait()); //头像
            jazUserCommentDO.setName(userDO.getNickname()); //昵称

            List<String> list = splitStrArrayList(jazUserCommentDO.getCommentDescriptionId());

            List<String> commentDescriptions  = JazUserCommentDescriptionService.selectBatchIds(list).stream()
                    .map(JazUserCommentDescriptionDO::getCommentDescription) // 提取commentDescription字段
                    .collect(Collectors.toList()); // 将结果收集到List中;

            jazUserCommentDOS.get(i).setCommentDescriptionContext(commentDescriptions);
        }
        return Result.ok(jazUserCommentDOS);
    }





    /**
     * 订单状态 (0：待分享，1：待使用，2：已取消，3：已退款)
     * @return
     */
    @GetMapping("/selUserOrder")
    public Result<Page<JazGroupOrderDO>> selUserOrder(JazGroupOrderDO jazGroupOrderDO,Integer status){
        UserDO getUser = JWTUtil.getUser();//获取登录用户
//        UserDO getUser = new UserDO();
//        getUser.setId(1504759468294201346L);
        Wrapper<JazGroupOrderDO> jazGroupOrderDOWrapper = new EntityWrapper<>();
        jazGroupOrderDOWrapper.eq("user_id",getUser.getId());
        jazGroupOrderDOWrapper.eq("order_status",status);
        if (status == 3){
            jazGroupOrderDOWrapper.eq("wx_status", "用户已取消");
        }else {
            jazGroupOrderDOWrapper.eq("wx_status", "支付成功");
        }
        jazGroupOrderDOWrapper.orderBy("create_time",false);
        Page<JazGroupOrderDO> page = new Page<JazGroupOrderDO>(jazGroupOrderDO.getCurrent(),jazGroupOrderDO.getSize());
        Page<JazGroupOrderDO> jazGroupOrderDOPage = jazGroupOrderService.selectPage(page, jazGroupOrderDOWrapper);

        for (int i=0;i<jazGroupOrderDOPage.getRecords().size();i++){
            JazGroupOrderDO records = jazGroupOrderDOPage.getRecords().get(i);
            JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(records.getGroupSpecsId());
            JazGroupProdDO jazGroupProdDO = jazGroupProdService.selectById(records.getGroupProdId());
            jazGroupOrderDOPage.getRecords().get(i).setGroupOrderName(jazGroupSpecsDO.getName());
            jazGroupOrderDOPage.getRecords().get(i).setGroupOrderImg(jazGroupProdDO.getImage());
            Date createTime = records.getCreateTime(); //订单创建时间
            Integer validTime = jazGroupProdDO.getValidTime(); //几个月后到期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createTime);
            calendar.add(Calendar.MONTH, validTime);
            Date entDate = calendar.getTime();
            //订单结束时间 = createTime + validTime 几个月后到期
            jazGroupOrderDOPage.getRecords().get(i).setEntDate(entDate);
            List<UserDO> userDOS = jazGroupActivityService.getUserByActivityId(records.getGroupActivityId());//查询参团人员
            jazGroupOrderDOPage.getRecords().get(i).setSum(jazGroupProdDO.getPeopleNum() - userDOS.size()); //还差几人
        }

        return Result.ok(jazGroupOrderDOPage);
    }




    /**
     * 订单详情查询
     * @return
     */
    @GetMapping("/selUserOrderDetails")
    public Result<JazGroupOrderDO> selUserOrderDetails(String id){
        JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectById(id);
        JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(jazGroupOrderDO.getGroupSpecsId());
        JazGroupProdDO jazGroupProdDO = jazGroupProdService.selectById(jazGroupOrderDO.getGroupProdId());

        jazGroupOrderDO.setGroupOrderName(jazGroupSpecsDO.getName());
        jazGroupOrderDO.setGroupOrderImg(jazGroupProdDO.getImage());
        jazGroupOrderDO.setEntDate(new Date());   //这里未处理！！！！！！！！！！！！！！！！
        return Result.ok(jazGroupOrderDO);
    }






    /**
     * 修改订单地址
     * @return
     */
    @PostMapping("/upOrderAddress")
    public Result upOrderAddress(String orderId,String receivingName,String phone,String province,String city,String district,String address){
        JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectById(orderId);
        jazGroupOrderDO.setReceivingName(receivingName);
        jazGroupOrderDO.setPhone(phone);
        jazGroupOrderDO.setProvince(province);
        jazGroupOrderDO.setCity(city);
        jazGroupOrderDO.setDistrict(district);
        jazGroupOrderDO.setAddress(address);
        jazGroupOrderService.updateById(jazGroupOrderDO);
        return Result.ok();
    }










    /**
     * 发起团购
     * @return
     */
    @PostMapping("/sponsorGroupActivity")
    public Result sponsorGroupActivity(String openid,Long groupProdId,Long groupSpecsId){
        UserDO getUser = JWTUtil.getUser();//获取登录用户
        JazGroupProdDO jazGroupProdDO = jazGroupProdService.selectById(groupProdId); //查询团购商品信息
        Wrapper<JazGroupActivityDO> jazGroupActivityWrapper = new EntityWrapper<>();
        jazGroupActivityWrapper.eq("group_prod_id",groupProdId); //拼团活动id
        JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(groupSpecsId); //查询团购商品规格信息
        List<JazGroupActivityDO> isGroupActivitys = jazGroupActivityService.selectList(jazGroupActivityWrapper); //查询该商品发起的团购

        for (JazGroupActivityDO jazGroupActivityDO:isGroupActivitys){
            Wrapper<JazGroupActivityUserDO> groupActivityUserWapper = new EntityWrapper<>();
            groupActivityUserWapper.eq("group_activity_id",jazGroupActivityDO.getId());
            groupActivityUserWapper.eq("user_id",getUser.getId()); //用户id
            JazGroupActivityUserDO is = jazGroupActivityUserService.selectOne(groupActivityUserWapper);
            if (is!=null){
                return Result.fail("拼团失败，每个用户只能参与一次");
            }
        }

        //新增订单
        JazGroupOrderDO jazGroupOrderDO =new JazGroupOrderDO();
        jazGroupOrderDO.setGroupSpecsId(groupSpecsId); //规格id
        jazGroupOrderDO.setGroupProdId(groupProdId); //商品id
        jazGroupOrderDO.setOrderNo(generateOrderNumber(20)); //生成20位订单编号
        jazGroupOrderDO.setUserId(getUser.getId());//用户id
//        jazGroupOrderDO.setAddressId(addressId); //地址id
//        JazShippingAddressDO jazShippingAddressDO = jazShippingAddressService.selectById(addressId);
//        jazGroupOrderDO.setPhone(jazShippingAddressDO.getPhone()); //收货手机号
//        jazGroupOrderDO.setReceivingName(jazShippingAddressDO.getReceivingName()); //收货人姓名
//        jazGroupOrderDO.setProvince(jazShippingAddressDO.getProvince()); //省
//        jazGroupOrderDO.setCity(jazShippingAddressDO.getCity());//市
//        jazGroupOrderDO.setDistrict(jazShippingAddressDO.getDistrict()); //区县
//        jazGroupOrderDO.setAddress(jazShippingAddressDO.getAddress()); //详细地址
        jazGroupOrderDO.setOrderStatus(0);//订单状态，默认待分享
        jazGroupOrderDO.setCreateTime(new Date()); //订单创建时间
        jazGroupOrderDO.setShareMoney(jazGroupSpecsDO.getGroupPrice()); //实付款
        jazGroupOrderDO.setAccountMoney(jazGroupSpecsDO.getGroupPrice()); //应付款
        jazGroupOrderDO.setWxOrderNo(OrderNoUtils.getOrderNo()); //商户订单编号
        jazGroupOrderDO.setWxOrderName(jazGroupSpecsDO.getName()); //商品订单名称
        jazGroupOrderDO.setWxStatus(OrderStatus.NOT_PAY.getType()); //订单状态
        jazGroupOrderDO.setOrderPayType(1);//2团购购买
        jazGroupOrderService.insert(jazGroupOrderDO);

        Map<String, Object> map;
        //调用系统微信小程序支付
        try {
            map = wxPayCommonService.jsapiNativePay(jazGroupOrderDO.getWxOrderName(),ConstAppId.USER_APP, openid, jazGroupOrderDO.getShareMoney(),jazGroupOrderDO.getWxOrderNo(), WxNotifyType.GROUP_NATIVE_NOTIFYS.getType());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok(map);
    }



    /**
     * 查询登录用户的团购拼团信息
     * @return
     */
    @GetMapping("/selGroupActivity")
    public Result<groupActivityVO> sponsorGroupProd(Long groupProdId){
        //定义最终返回数据
        groupActivityVO groupActivityVO =new groupActivityVO();
        JazGroupProdDO jazGroupProdDO = jazGroupProdService.selectById(groupProdId);
        groupActivityVO.setSum(jazGroupProdDO.getPeopleNum()); //几人成团
        Integer countDown = jazGroupProdDO.getCountDown(); //拼团倒计时，以小时为单位
        UserDO getUser = JWTUtil.getUser();
//        UserDO getUser = new UserDO();
//        getUser.setId(1685834029766819841L);
        Long groupActivityId = jazGroupActivityService.getGroupActivityIdByUserIdGropProdId(getUser.getId(),groupProdId);
        JazGroupActivityDO jazGroupActivityDO = jazGroupActivityService.selectById(groupActivityId);
        groupActivityVO.setGroupActivityId(jazGroupActivityDO.getId()); //团购id
        groupActivityVO.setState(jazGroupActivityDO.getStatus()); //封面

        JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(jazGroupActivityDO.getGroupSpecsId()); //查询拼团的规格
        groupActivityVO.setGroupName(jazGroupSpecsDO.getName()); //名称
        groupActivityVO.setGroupPrice(jazGroupSpecsDO.getGroupPrice()); //价格
        groupActivityVO.setGroupImg(jazGroupProdDO.getImage()); //封面

        //创建时间 + 拼团倒计时 = 结束时间
        Date endDate = addHoursToDate(jazGroupActivityDO.getCreateTime(), countDown);
        String countDownSSS = String.valueOf(calculateRemainingSeconds(endDate)); //倒计时秒
        groupActivityVO.setCountDown(countDownSSS);

        List<UserDO> userDOS = jazGroupActivityService.getUserByActivityId(jazGroupActivityDO.getId());//查询参团人员
        groupActivityVO.setPoorSum(jazGroupProdDO.getPeopleNum() - userDOS.size()); //还差几人
        UserDO userDO = userService.selectById(jazGroupActivityDO.getSponsorUserId()); //查询拼团发起人
        groupActivityVO.setName(userDO.getNickname()); //用户名
        groupActivityVO.setUserList(userDOS);
        return Result.ok(groupActivityVO);
    }




    /**
     * 参与拼团
     * @return
     */
    @PostMapping("/participationGroupProd")
    public Result participationGroupProd(String openid,Long groupActivityId){
                UserDO getUser = JWTUtil.getUser();//获取登录用户
//        UserDO getUser = new UserDO();
//        getUser.setId(1685834029766819841L);
        Long userId = getUser.getId();
        JazGroupActivityDO jazGroupActivity = jazGroupActivityService.selectById(groupActivityId); //查询拼团信息
        JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(jazGroupActivity.getGroupSpecsId()); //查询团购商品规格信息
        if (jazGroupActivity.getStatus() == 1){
            return Result.fail("拼团失败，该订单已完成拼团！");
        }
        if(userIsGroupActivity(jazGroupActivity.getId(),userId) == 1){
            return Result.fail("拼团失败，每个用户只能参与一次");
        }

        //新增订单
        JazGroupOrderDO jazGroupOrderDO =new JazGroupOrderDO();
        jazGroupOrderDO.setGroupSpecsId(jazGroupActivity.getGroupSpecsId()); //规格id
        jazGroupOrderDO.setGroupProdId(jazGroupActivity.getGroupProdId()); //商品id
        jazGroupOrderDO.setGroupActivityId(groupActivityId); //团购活动表id
        jazGroupOrderDO.setOrderNo(generateOrderNumber(20)); //生成20位订单编号
        jazGroupOrderDO.setUserId(userId);//用户id
//        jazGroupOrderDO.setAddressId(addressId); //地址id
//        JazShippingAddressDO jazShippingAddressDO = jazShippingAddressService.selectById(addressId);
//        jazGroupOrderDO.setReceivingName(jazShippingAddressDO.getReceivingName()); //收货人姓名
//        jazGroupOrderDO.setPhone(jazShippingAddressDO.getPhone()); //收货手机号
//        jazGroupOrderDO.setProvince(jazShippingAddressDO.getProvince()); //省
//        jazGroupOrderDO.setCity(jazShippingAddressDO.getCity());//市
//        jazGroupOrderDO.setDistrict(jazShippingAddressDO.getDistrict()); //区县
//        jazGroupOrderDO.setAddress(jazShippingAddressDO.getAddress()); //详细地址
        jazGroupOrderDO.setOrderStatus(0);//订单状态，默认待分享
        jazGroupOrderDO.setCreateTime(new Date()); //订单创建时间
        jazGroupOrderDO.setShareMoney(jazGroupSpecsDO.getGroupPrice()); //实付款
        jazGroupOrderDO.setAccountMoney(jazGroupSpecsDO.getGroupPrice()); //应付款
        jazGroupOrderDO.setWxOrderNo(OrderNoUtils.getOrderNo()); //商户订单编号
        jazGroupOrderDO.setWxOrderName(jazGroupSpecsDO.getName()); //商品订单名称
        jazGroupOrderDO.setWxStatus(OrderStatus.NOT_PAY.getType()); //订单状态
        jazGroupOrderDO.setOrderPayType(1);//1团购购买
        jazGroupOrderService.insert(jazGroupOrderDO);

        Map<String, Object> map;
        //调用系统微信小程序支付
        try {
            map = wxPayCommonService.jsapiNativePay(jazGroupOrderDO.getWxOrderName(), ConstAppId.USER_APP,openid, jazGroupOrderDO.getShareMoney(),jazGroupOrderDO.getWxOrderNo(), WxNotifyType.CY_GROUP_NATIVE_NOTIFYS.getType());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok(map);
    }


    /**
     * 获取拼团用户的最大排序号
     * @param groupActivityId
     * @return
     */
    private Integer getActityUserSortMax(Long groupActivityId){
        List<UserDO> userDOS = jazGroupActivityService.getUserByActivityId(groupActivityId);//查询参团人员
        UserDO userDO = userDOS.get(userDOS.size()-1); //获取排序后的最后一条数据
        Wrapper<JazGroupActivityUserDO> jazGroupActivityUserDOEntityWrapper = new EntityWrapper<>();
        jazGroupActivityUserDOEntityWrapper.eq("group_activity_id",groupActivityId);
        jazGroupActivityUserDOEntityWrapper.eq("user_id",userDO.getId());
        JazGroupActivityUserDO jazGroupActivityUserDO = jazGroupActivityUserService.selectOne(jazGroupActivityUserDOEntityWrapper);
        Integer sort = jazGroupActivityUserDO.getSort();
        return sort;
    }



    /**
     * 判断该用户是否可以拼团，参团。0可以，1不可以
     * @param groupActivityId 团购id
     * @param userId 用户id
     * @return
     */
    private Integer userIsGroupActivity(Long groupActivityId,Long userId){
        Integer r = 0; //默认可以拼团
        JazGroupActivityDO isGroupActivitys = jazGroupActivityService.selectById(groupActivityId); //查询该团购
        Wrapper<JazGroupActivityUserDO> groupActivityUserWapper = new EntityWrapper<>();
        groupActivityUserWapper.eq("group_activity_id",isGroupActivitys.getId());
        groupActivityUserWapper.eq("user_id",userId); //用户id
        JazGroupActivityUserDO is = jazGroupActivityUserService.selectOne(groupActivityUserWapper);
        if (is!=null){
            r = 1;
        }
        return r;
    }




    /**
     * 拼团倒计时结束或者人满调用该方法结束拼团。
     */
    private void expireOrder(Long groupId) {
        System.out.println("团购 " + groupId + " 已过期！");
        JazGroupActivityDO jazGroupActivityDO = jazGroupActivityService.selectById(groupId);
        if (jazGroupActivityDO.getStatus()!=1){
            jazGroupActivityDO.setStatus(1); //设置状态为已完成。
            jazGroupActivityService.updateById(jazGroupActivityDO);
        }
        //查询该拼团下面的用户
        Wrapper<JazGroupActivityUserDO> groupActivityUserWapper = new EntityWrapper<>();
        groupActivityUserWapper.eq("group_activity_id",jazGroupActivityDO.getId());
        List<JazGroupActivityUserDO> jazGroupActivityUserDOS = jazGroupActivityUserService.selectList(groupActivityUserWapper);
        for (int i =0;i<jazGroupActivityUserDOS.size();i++){
            Wrapper<JazGroupOrderDO> groupOrderDOEntityWrapper = new EntityWrapper<>();
            groupOrderDOEntityWrapper.eq("user_id",jazGroupActivityUserDOS.get(i).getUserId());
            groupOrderDOEntityWrapper.eq("group_prod_id",jazGroupActivityDO.getGroupProdId());
            groupOrderDOEntityWrapper.eq("group_specs_id",jazGroupActivityDO.getGroupSpecsId());
            JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectOne(groupOrderDOEntityWrapper);
            if (jazGroupOrderDO.getOrderStatus() == 0) {
                jazGroupOrderDO.setOrderStatus(1);//待使用
                jazGroupOrderService.updateById(jazGroupOrderDO);
            }
        }
    }


    /**
     * 方法用于设置倒计时并自动结束订单  异步方法，以秒为单位
     * @param countdownSeconds  倒计时秒数
     * @param groupId  团购活动id
     */
    @Async
    public void setCountdownAndExpire(int countdownSeconds,Long groupId) {
        // 计算到期时间
        Date currentTime = new Date();
        long expireTimeMillis = currentTime.getTime() + (countdownSeconds * 1000); // 将秒转换为毫秒
        Date expireTime = new Date(expireTimeMillis);

        // 设置定时器，在到期时间时自动结束订单
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                expireOrder(groupId);
            }
        }, expireTime);
    }




    /**
     * 计算从当前时间到给定时间的剩余秒数
     *
     * @param targetTime 给定时间
     * @return 剩余秒数
     */
    public static long calculateRemainingSeconds(Date targetTime) {
        // 获取当前时间
        Date currentTime = new Date();

        // 计算剩余秒数
        long timeDifferenceInMillis = targetTime.getTime() - currentTime.getTime();
        long remainingSeconds = timeDifferenceInMillis / 1000;

        // 如果时间已经过去了，则剩余秒数为负数，将其设为0
        if (remainingSeconds < 0) {
            remainingSeconds = 0;
        }

        return remainingSeconds;
    }


    /**
     * 将指定的日期往前加几小时
     * @param date 日期
     * @param hours 小时
     * @return
     */
    public static Date addHoursToDate(Date date, int hours) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, hours);
        return calendar.getTime();
    }


    // 生成指定位数订单编号的方法
    public static String generateOrderNumber(int length) {
        // 检查长度是否合法
        if (length <= 0) {
            throw new IllegalArgumentException("订单编号长度必须大于0");
        }

        // 计算随机部分的长度
        int randomPartLength = length - 14; // 时间戳部分长度为14

        // 如果随机部分长度小于等于0，则直接使用时间戳作为订单编号
        if (randomPartLength <= 0) {
            return generateTimestamp();
        }

        // 生成随机部分
        String randomPart = generateRandomDigits(randomPartLength);

        // 组合时间戳部分和随机部分，形成订单编号
        String orderNumber = generateTimestamp() + randomPart;

        return orderNumber;
    }

    // 生成时间戳部分
    private static String generateTimestamp() {
        LocalDateTime now = LocalDateTime.now();
        return now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    }

    // 生成指定长度的随机数字字符串
    private static String generateRandomDigits(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(random.nextInt(10)); // 生成0到9之间的随机数字
        }
        return builder.toString();
    }
















    /**
     * 单独购买接口
     * @return
     */
    @PostMapping("/buyGroupActivity")
    public Result buyGroupActivity(String openid,Long groupProdId,Long groupSpecsId, Long addressId,Integer number){
        //购买数量是几，就创建几条订单
        Assert.notNull(number,"请选择购买数量");
        JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(groupSpecsId);
        UserDO getUser = JWTUtil.getUser();
        String wxOrderNo = OrderNoUtils.getOrderNo();
        for (Integer i = 0; i < number; i++) {
            JazGroupOrderDO jazGroupOrderDO =new JazGroupOrderDO();
            jazGroupOrderDO.setGroupSpecsId(groupSpecsId); //规格id
            jazGroupOrderDO.setGroupProdId(groupProdId); //商品id
            jazGroupOrderDO.setOrderNo(generateOrderNumber(20)); //生成20位订单编号
            jazGroupOrderDO.setUserId(getUser.getId());//用户id
            jazGroupOrderDO.setOrderStatus(1);//订单状态，默认待使用
            jazGroupOrderDO.setCreateTime(new Date()); //订单创建时间
            jazGroupOrderDO.setShareMoney(jazGroupSpecsDO.getPrice()); //实付款
            jazGroupOrderDO.setAccountMoney(jazGroupSpecsDO.getPrice()); //应付款
            jazGroupOrderDO.setWxOrderNo(wxOrderNo); //商户订单编号
            jazGroupOrderDO.setWxOrderName(jazGroupSpecsDO.getName()); //商品订单名称
            jazGroupOrderDO.setWxStatus(OrderStatus.NOT_PAY.getType()); //订单状态
            jazGroupOrderDO.setOrderPayType(0);//1单独购买
            jazGroupOrderDO.setNumber(number);
            jazGroupOrderService.insert(jazGroupOrderDO);
        }

        Map<String, Object> map;
        //调用系统微信小程序支付
        try {
           map = wxPayCommonService.jsapiNativePay(jazGroupSpecsDO.getName(), ConstAppId.USER_APP,openid, jazGroupSpecsDO.getPrice().multiply(new BigDecimal(number)),wxOrderNo, WxNotifyType.GROUP_NATIVE_NOTIFYS.getType());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok(map);
    }








    /**
     * 团购订单退款接口
     * @return
     */
    @Transactional
    @PostMapping("/groupOrderRefund")
    public Result<?>  groupOrderRefund(String orderNo,String msg) {

        String[] wxOrderNos = orderNo.split(",");
        Result<?> result = new Result<>();
        for (String order : wxOrderNos) {
            //1.查询需要退款的的订单
            JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectOne(new EntityWrapper<JazGroupOrderDO>().eq("order_no",order));
            jazGroupOrderDO.setRefundRemark(msg);
            jazGroupOrderService.updateById(jazGroupOrderDO);

            //查询购买数量 退款需要知道支付总金额
            int i = jazGroupOrderService.selectCount(new EntityWrapper<JazGroupOrderDO>().eq("wx_order_no", jazGroupOrderDO.getWxOrderNo()));
            //2.调用系统微信小程序退款
            try {

                result = wxPayCommonService.jsapiRefund(jazGroupOrderDO.getWxTransactionId(), jazGroupOrderDO.getOrderNo(), jazGroupOrderDO.getShareMoney().multiply(new BigDecimal(i)), jazGroupOrderDO.getShareMoney());

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return result;

    }


    /**
     * 团购去使用
     * @param orderId   团购订单id
     * @param receivingName  姓名
     * @param phone  手机号
     * @param province 省份
     * @param city 市
     * @param district 区
     * @param address 详细地址
     * @param startTime  开始时间
     * @return
     */
    @Transactional
    @PostMapping("/groupOrderEmploy")
    public Result<?>  groupOrderEmploy(Long orderId,String receivingName,String phone,String province,String city,String district,String address,Date startTime,String remark) {
        JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectById(orderId);

        JazUserOrderDO jazUserOrderDO = new JazUserOrderDO();
        jazUserOrderDO.setInitiateId(jazGroupOrderDO.getUserId());  //订单发起人id
        jazUserOrderDO.setTotalPrice(jazGroupOrderDO.getShareMoney()); //实付款
        jazUserOrderDO.setStatus(0); //默认去使用，订单状态为待开始。
        jazUserOrderDO.setConcludeStatus(2); //默认合同签署状态为已签署
        jazUserOrderDO.setAddress(province + city + district + address); //服务地址

        //这里的服务类型只能是保洁
        EntityWrapper<JazSysProjectDO> wrapper =new EntityWrapper();
        wrapper.eq("name","保洁");
        JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectOne(wrapper);
        if (jazSysProjectDO != null){
            jazUserOrderDO.setProjectId(String.valueOf(jazSysProjectDO.getId()));  //服务类型
        }
        jazUserOrderDO.setCreateTime(new Date()); //创建时间
        jazUserOrderDO.setStartTime(startTime); //服务开始时间

        JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(jazGroupOrderDO.getGroupSpecsId());

        int s = extractNumbers(jazGroupSpecsDO.getName()); //获取保洁几小时
        jazUserOrderDO.setEndTime(addHoursToDate(startTime,s)); //服务结束时间
        jazUserOrderDO.setNameJia(receivingName);//甲方姓名
        jazUserOrderDO.setPhoneJia(phone);//甲方手机号
        jazUserOrderDO.setRemark(remark); //订单备注，描述
        jazUserOrderDO.setNumber(jazGroupOrderDO.getOrderNo());//订单编号
        jazUserOrderDO.setProductId(jazGroupSpecsDO.getId()); //商品规格id
        jazUserOrderDO.setOrderPayType(jazGroupOrderDO.getOrderPayType()); //订单状态 团购，还是单独购买
        jazUserOrderDO.setOrderType(1); //订单类型，团购
        jazUserOrderService.insert(jazUserOrderDO);
        jazGroupOrderService.updateById(jazGroupOrderDO);
        return Result.ok();
    }




    private int extractNumbers(String input) {
        // 使用正则表达式匹配数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(input);

        // 如果找到了数字，则返回第一个匹配到的数字
        if (matcher.find()) {
            return Integer.parseInt(matcher.group());
        } else {
            // 如果没有找到数字，则返回 0
            return 0;
        }
    }


}
